package marcis.jarina.appengine;

import au.com.bytecode.opencsv.CSVReader;
import marcis.jarina.hibernate.entities.Archive;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class CSVServiceImpl implements CSVService {

    private static final Logger logger = Logger.getLogger(CSVServiceImpl.class);


    @Override
    public Map<String, String> getArchiveToArchiveList(byte[] bytes) {
        return null;
    }

    @Override
    public List<Archive> getArchiveList(InputStream stream) throws IOException {
        Reader reader = new BufferedReader(new InputStreamReader(stream));
        CSVReader csvReader = new CSVReader(reader, ',');
        List<String[]> list = csvReader.readAll();
        csvReader.close();
        List<Archive> result = new ArrayList<Archive>();
        for(String[] line : list) {
            Archive archive = convertLineToArchive(line);
            result.add(archive);
        }
        return result;
    }

    private Archive convertLineToArchive(String[] line) {
        Archive archive = new Archive();
        archive.setId(Integer.valueOf(line[0]));
        archive.setArtifactId(line[1]);
        //TODO does not work cos CSVReader automaticaly unEscape so  line[XX] is already wrong!
        // may be better to save only fileName anyway
        //archive.setFilePath(escapeEasy(line[2]));
        archive.setFilePath("not supported yet");
        archive.setGroupId(line[3]);
        archive.setStoreDate(line[4]);
        archive.setVersion(line[5]);
        return archive;
    }

}
